import { findShowMenu, menusTreeToList, findTreeParent, findMenuFirstChild } from '@/utils/menus'

const state = {
  originalMenus: [], // 原来菜单
  menus: [], // 所有菜单
  sidebarMenus: {
    System: [],
    Mch: [],
    Sp: []
  }, // 侧边栏菜单
  activeSidebarMenusCode: 'System',
  activeSidebarMchId: null,
  activeSidebarMchInfo: null,
  activeSidebarSpId: null,
  activeSidebarSpInfo: null,
  sidebarMenusPrevPageCode: '',
  sidebarMenusIndex: '',
  curMenu: null,
  codeMenu: null,
  homePageMenu: null
}

const mutations = {
  REFRESH_CUR_MENU: (state, router) => {
    state.activeSidebarMchId = router.query && router.query.mchId || null
    state.activeSidebarSpId = router.query && router.query.spId || null
    if (Object.keys(router.meta).length === 0) {
      state.activeSidebarMenusCode = 'System'
      return -1
    }
    const menuList = menusTreeToList(state.originalMenus)
    const parentList = findTreeParent(menuList, router.meta.id)
    const codeList = []
    for (let i = 0; i < parentList.length; i++) {
      codeList.push(parentList[i].code)
    }
    // function findParent(code, flattenTree) {
    //   const parentArr = [] // 存储所有的父级元素
    //   function find(code, flattenTree) {
    //     flattenTree.forEach(ele => {
    //       if (ele.code === code) {
    //         parentArr.unshift(ele.code)
    //         if (ele.parentId !== -1 && ele.parent && ele.parent.code) {
    //           find(ele.parent.code, flattenTree)
    //         }
    //       }
    //     })
    //   }
    //   find(code, flattenTree)
    //   return parentArr
    // }
    // const codeList = findParent(router.name, menuList)
    if (codeList.length) {
      switch (codeList[0]) {
        case 'Sp':
          state.activeSidebarMenusCode = 'Sp'
          state.sidebarMenusPrevPageCode = 'SystemSpManage'
          break
        case 'Mch':
          state.activeSidebarMenusCode = 'Mch'
          state.sidebarMenusPrevPageCode = 'SystemMchManage'
          break
        default:
          state.activeSidebarMenusCode = 'System'
          break
      }
    } else {
      state.activeSidebarMenusCode = 'System'
    }
  },

  RELOAD_MENUS: (state, menus) => {
    const allMenu = JSON.parse(JSON.stringify(menus))
    findShowMenu(allMenu) // TODO 暂时测试用
    allMenu.forEach(v => {
      switch (v.code) {
        case 'System':
        case 'Mch':
        case 'Sp':
          state.sidebarMenus[v.code] = v.children || []
          break
      }
    })
    state.originalMenus = menus
    state.menus = allMenu
    state.homePageMenu = findMenuFirstChild(allMenu)
  }
}

const actions = {
  ReloadMenus: ({ commit }, menus) => {
    commit('RELOAD_MENUS', menus)
  },
  RefreshCurMenu: ({ commit }, router) => {
    commit('REFRESH_CUR_MENU', router)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

